package cn.com.easy.permission.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.easy.permission.dao.ResourceDao;
import cn.com.easy.permission.model.ResourceModel;
import cn.com.easy.permission.service.system.urlreserve.UrlReserveService;
import cn.com.easy.permission.service.system.urlreserve.UrlResourceEntity;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;

import com.google.common.collect.Lists;

/**
 * 反射url资源 控制器
 * 
 * @author nibili 2015年12月13日上午12:58:16
 * 
 */
@Controller
@RequestMapping("/manage/system/url/reserve")
public class SystemUrlReverseController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SystemUrlReverseController.class);

	/** 反射controller的url资源 */
	@Autowired
	private UrlReserveService urlReserveService;
	/** 权限资源表dao */
	@Autowired
	private ResourceDao resourceDao;

	/**
	 * 首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("首页")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/system/system_url_reserve/system_url_reserve";
	}

	/**
	 * 获取所有成员
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取所有成员")
	@RequestMapping("/get/all")
	public void getAllMembers(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {

			Page<UrlResourceEntity> springDataPage = new PageImpl<UrlResourceEntity>(urlReserveService.getUrlResources());
			cn.com.easy.utils.Page<UrlResourceEntity> page = PageUtils.getPage(springDataPage);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取权限树
	 * 
	 * @param request
	 * @param response
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取权限树")
	@RequestMapping("/get/resource/all")
	public void getAllAuthorization(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ResourceModel> list = resourceDao.findAll(new Sort(new Order(Direction.ASC, "showIndex")));
			if (CollectionUtils.isEmpty(list) == true) {
				// 初始根节点
				ResourceModel resourceModelTemp = new ResourceModel();
				resourceModelTemp.setName("根");
				resourceModelTemp.setCreateBy(this.getCurrentUser(request).getLoginname());
				resourceModelTemp = resourceDao.save(resourceModelTemp);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, Lists.newArrayList(resourceModelTemp)));
			} else {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, list));
			}

		} catch (Exception ex) {
			logger.error("获取所有成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取权限树异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 保存url到资源库中
	 * 
	 * @param request
	 * @param response
	 * @param names
	 *            名称集合
	 * @param paths
	 *            路径集合
	 * @param resourceId
	 * @author nibili 2017年12月11日
	 */
	@UrlReserveAnotion("保存url到资源库中")
	@RequestMapping(value = "/save/resource", method = RequestMethod.POST)
	public void saveResource(HttpServletRequest request, HttpServletResponse response, String[] names, String[] paths, Long resourceId) {
		try {
			if (ArrayUtils.isEmpty(names) == true) {
				// ResponseOutputUtils.renderJson(response,
				// MessageDTO.newInstance("", false, "功能菜单名称不能为空~"));
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "功能菜单数量不能为空~"));
			} else if (ArrayUtils.isEmpty(paths) == true) {
				// ResponseOutputUtils.renderJson(response,
				// MessageDTO.newInstance("", false, "功能菜单路径不能为空~"));
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "功能菜单路径数量不能为空~"));
			} else if (names.length != paths.length) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, " 菜单与菜单路径数量不一致"));
			} else if (resourceId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "父级id不能为空~"));
			} else {

				for (int i = 0, len = names.length; i < len; i++) {

					String name = names[i];
					String path = paths[i];

					ResourceModel resourceModelTemp = new ResourceModel();
					resourceModelTemp.setName(name);
					resourceModelTemp.setUrl(path);
					resourceModelTemp.setParentId(resourceId);
					resourceModelTemp.setCreateBy(this.getCurrentUser(request).getLoginname());
					resourceDao.save(resourceModelTemp);

				}

				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("保存url到资源库中异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "保存url到资源库中异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
